package cqrtplm.service.impl;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.convert.Convert;
import com.alibaba.fastjson.JSONObject;
import com.hustcad.plm.pdm.common.model.vo.BusinessObjectVO;
import com.hustcad.plm.pdm.common.model.vo.iteration.CommonIteratorVO;
import com.hustcad.plm.pdm.ec.mapper.TyplmChgNoticeActivityLinkMapper;
import com.hustcad.plm.pdm.ec.module.dto.ECObjDTO;
import com.hustcad.plm.pdm.ec.module.dto.ECObjData;
import com.hustcad.plm.pdm.ec.module.vo.ChgActivityVO;
import com.hustcad.plm.pdm.ec.module.vo.ChgNoticeVO;
import com.hustcad.plm.pdm.ec.service.*;
import com.hustcad.plm.pdm.flowbusiness.service.TyplmFlowChgFormActivityViewService;
import com.hustcad.plm.pdm.iteration.service.TyplmIterationService;
import com.hustcad.plm.pdm.partbom.service.TyplmPartService;
import com.hustcad.plm.pdm.partbom.service.TyplmPartUsageLinkService;
import com.hustcad.plm.pdm.partbom.vo.PartDetailsVO;
import com.hustcad.plm.pdm.workflow.service.TyplmWorkFlowContainerService;
import com.ty.basic.entity.IdentifierEntity;
import com.ty.basic.entity.change.ChgActivityDO;
import com.ty.basic.entity.part.PartDO;
import cqrtplm.constant.RTPlmConstant;
import cqrtplm.mapper.RTChangeMapper;
import cqrtplm.service.*;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.math.BigInteger;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.function.Function;
import java.util.stream.Collectors;

/**
 * Description xxx
 *
 * @auther: xxx
 * @date: xxx
 */
@Slf4j
@Service
public class TestServiceImpl implements TestService {
    @Resource
    OperateChangeObjectService operateChangeObjectService;
    @Resource
    RTChangeMapper rtChangeMapper;
    @Resource
    TyplmIterationService typlmIterationService;
    @Resource
    private TyChangeCheckService tyChangeCheckService;
    @Resource
    private TyChangeObjectLinkExtService changeObjectLinkExtService;
    @Resource
    private TyplmChgNoticeActivityLinkMapper typlmChgNoticeActivityLinkMapper;
    @Resource
    private TyplmChangeCommonService typlmChangeCommonService;
    @Resource
    private TyplmChangeEcEndItemLinkService typlmChangeEcEndItemLinkService;
    @Resource
    TyplmFlowChgFormActivityViewService typlmFlowChgFormActivityViewService;
    @Resource
    TyplmEngineeringChangeService typlmEngineeringChangeService;
    @Resource
    RTReviseObjectByEcnService rtReviseObjectByEcnService;
    @Resource
    RTCreateEcaByEcnService rtCreateEcaByEcnService;
    @Resource
    RTChangeNoticeService rtChangeNoticeService;
    @Resource
    TyplmWorkFlowContainerService typlmWorkFlowContainerService;
    @Resource
    SapIntegrityService sapIntegrityService;
    @Resource
    private TyplmPartUsageLinkService typlmPartUsageLinkService;
    @Resource
    private TyplmPartService typlmPartService;
    @Resource
    TyplmIterationService iterationService;
    @Resource
    TyplmChgActivityService typlmChgActivityService;
    @Resource
    TyplmChgNoticeActivityLinkService typlmChgNoticeActivityLinkService;
    @Resource
    private TyplmChgNoticeQueryService typlmChgNoticeQueryService;

    @SneakyThrows
    @Transactional
    @Override
    public JSONObject testFunc(LinkedHashMap map) {
        String number1 = map.get("number1").toString();
        String number2 = map.get("number2").toString();
        //        rtReviseObjectByEcnService.reviseEcaObjectByEcn(new BigInteger(number1));
        List list = new ArrayList();
        //        list.add(new BigInteger(number1));
        //        typlmWorkFlowContainerService.delete(list);
        //        this.typlmPartUsageLinkService.queryPartUsageLinkByAoidBoid();
        //        this.typlmPartUsageLinkService.batchDeletePartUsageLink();
        //        this.typlmPartUsageLinkService.batchInsertPartUsageLink();
        //        JSONObject json = rtChangeMapper.queryLatestMaterialByCode(number1, RTPlmConstant.VIEW_DESIGN);
        ChgNoticeVO chgNoticeVO = typlmChgNoticeQueryService.queryECOByNumber(number1);
        List<ChgActivityDO> chgActivityDOList = this.typlmChgNoticeActivityLinkService.queryECAByECNId(chgNoticeVO.getOid());
          if (!CollUtil.isEmpty(chgActivityDOList)) {
            Map<String, ChgActivityDO> ecaOwnerMap = (Map) chgActivityDOList.stream().collect(
                    Collectors.toMap((item) -> item.getOid() + "_" + item.getOwneroid(), Function.identity(),
                                     (a, b) -> a));
            if (CollUtil.isNotEmpty(ecaOwnerMap)) {
                List<ChgActivityVO> deleteList = Convert.toList(ChgActivityVO.class, ecaOwnerMap.values());
                this.typlmChgActivityService.batchDeleteEca(deleteList);
            }
        }
        //        List<DeleteDTO> list2=new ArrayList<>();
        //        DeleteDTO deleteDTO = new DeleteDTO();
        //        deleteDTO.setOid(new BigInteger(json.getString("OID")));
        //        deleteDTO.setOtype(json.getString("OTYPE"));
        //        deleteDTO.setDeleteType("latestRevision");
        //        list2.add(deleteDTO);
        //        this.commonDeleteService.productCommonDelete(list2);
        //        latestIteration
        //        allRevisions
        //        latestRevision
        //        List<PartUsageLinkDO> deleteLinkList=new ArrayList<>();
        //        List<Map<String, PartDetailsVO>> list1=new ArrayList<>();
        //        list1=queryChildPart(list1,json.getString("OID"),json.getString("OTYPE"));
        //            List<DeleteDTO> list2=new ArrayList<>();
        //        for (Map<String, PartDetailsVO> map1 : list1) {
        //            PartDetailsVO  parent =map1.get("parent");
        //            PartDetailsVO  child =map1.get("child");
        //            DeleteDTO deleteDTO = new DeleteDTO();
        //            deleteDTO.setOid(new BigInteger(parent.getOid()));
        //            deleteDTO.setOtype(parent.getOtype());
        //            if (parent.getIteration().equals(1)){
        //
        //            deleteDTO.setDeleteType("latestRevision");
        //            }else {
        //                deleteDTO.setDeleteType("latestIteration");
        //            }

        //            list2.add(deleteDTO);
        //            deleteDTO = new DeleteDTO();
        //            deleteDTO.setOid(new BigInteger(child.getOid()));
        //            deleteDTO.setOtype(child.getOtype());
        //            if (child.getIteration().equals(1)){
        //
        ////                deleteDTO.setDeleteType("latestRevision");
        //            }else {
        ////                deleteDTO.setDeleteType("latestIteration");
        //            }

        //            list2.add(deleteDTO);
        //            List<PartUsageLinkDO> beforeUsageLinkList = typlmPartUsageLinkService.queryPartUsageLinkByAoidBoid(
        //                    new BigInteger(parent.getOid()), new BigInteger(child.getMasteredoid()));
        //            deleteLinkList.addAll(beforeUsageLinkList);
        //        }
        //        if (CollUtil.isNotEmpty(deleteLinkList)) {
        //            typlmPartUsageLinkService.batchDeletePartUsageLink(deleteLinkList);
        //                    this.commonDeleteService.productCommonDelete(list2);
        //        }
        return new JSONObject();
    }

    private List<Map<String, PartDetailsVO>> queryChildPart(List<Map<String, PartDetailsVO>> list, String oid,
                                                            String otype) {
        if (StringUtils.isNotBlank(oid) && StringUtils.isNotBlank(otype)) {
            PartDetailsVO parentDetailVO = this.typlmPartService.queryPartDetails(new BigInteger(oid), otype);
            List<PartDO> partDOS = this.rtChangeMapper.queryChildPart(oid, RTPlmConstant.VIEW_DESIGN);
            for (PartDO partDO : partDOS) {
                Map<String, PartDetailsVO> map = new HashMap<>();
                map.put("parent", parentDetailVO);
                BigInteger childOid = partDO.getOid();
                String childOType = partDO.getOtype();
                PartDetailsVO detailsVO = this.typlmPartService.queryPartDetails(childOid, childOType);
                map.put("child", detailsVO);
                list.add(map);
                queryChildPart(list, childOid.toString(), childOType);
            }
        }
        return list;
    }

    @Transactional
    @Override
    public List<ECObjDTO> newVersion(List<CommonIteratorVO> commonIteratorVOList) {
        List<BusinessObjectVO> gyEcnBatchNewversionList = typlmIterationService.batchNewVersionWithPolicy(
                commonIteratorVOList);
        return convertBusinessObjToEcoObj(gyEcnBatchNewversionList);
    }

    private List<BusinessObjectVO> getBusinessObjectVOS(List<ECObjData> list) {
        List<CommonIteratorVO> commonIteratorVOList = new ArrayList<>();
        for (ECObjData ecObjData : list) {
            CommonIteratorVO commonIteratorVO = new CommonIteratorVO();
            commonIteratorVO.setId(String.valueOf(ecObjData.getOid()));
            commonIteratorVO.setTypeDefName(ecObjData.getOtype());
            commonIteratorVO.setChangePolicy("Change");
            commonIteratorVOList.add(commonIteratorVO);
        }
        return typlmIterationService.batchNewVersionWithPolicy(commonIteratorVOList);
    }

    /**
     * 添加物料至变更后
     *
     * @param entityList
     * @param oid
     */
    private void addObjectTOChgAfter(List<ECObjDTO> entityList, BigInteger oid) {
        this.tyChangeCheckService.checkChangeObjectAfterCheck(entityList);
        List<ChgActivityDO> ecaList = this.typlmChgNoticeActivityLinkMapper.queryECAByECNId(oid);
        if (CollUtil.isEmpty(ecaList)) {
            return;
        }
        ChgActivityDO chgActivityDO = ecaList.get(0);
        IdentifierEntity identifierEntity = new IdentifierEntity(chgActivityDO.getOid(), chgActivityDO.getOtype());
        this.changeObjectLinkExtService.createECObjDataLinkList(identifierEntity, entityList, Boolean.FALSE);
    }

    //转换为可挂接的变更后对象
    private List<ECObjDTO> convertBusinessObjToEcoObj(List<BusinessObjectVO> businessObjectVOS) {
        List<ECObjDTO> entityList = new ArrayList<>();
        for (BusinessObjectVO objectVO : businessObjectVOS) {
            ECObjDTO ecObjDTO = new ECObjDTO();
            ecObjDTO.setOtype(objectVO.getTypeDefName());
            ecObjDTO.setOid(objectVO.getId());
            entityList.add(ecObjDTO);
        }
        return entityList;
    }
}